import { Injectable } from '@angular/core';
import {
  HttpErrorResponse,
  HttpClient,
  HttpHeaders
} from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError, Observable } from 'rxjs';
import { AsyncData } from '../models/async-data';
import { authToken } from '../functions/utils';
import { Router } from '@angular/router';
const mergeUrl = url => 'http://localhost:5872/api' + url;
@Injectable({
  providedIn: 'root'
})
export class HttpService {
  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
      Authorization: `Bearer ${localStorage.getItem(authToken)}`
    })
  };
  constructor(private http: HttpClient, private router: Router) {}
  get<T>(url: string): Observable<AsyncData<T>> {
    return this.http
      .get<AsyncData<T>>(mergeUrl(url), this.httpOptions)
      .pipe(catchError((err: HttpErrorResponse) => this.handleError(err)));
  }
  post<T>(url: string, data: any): Observable<AsyncData<T>> {
    return this.http
      .post<AsyncData<T>>(mergeUrl(url), data, this.httpOptions)
      .pipe(catchError((err: HttpErrorResponse) => this.handleError(err)));
  }
  put<T>(url: string, data: any): Observable<AsyncData<T>> {
    return this.http
      .put<AsyncData<T>>(mergeUrl(url), data, this.httpOptions)
      .pipe(catchError((err: HttpErrorResponse) => this.handleError(err)));
  }
  delete<T>(url: string): Observable<AsyncData<T>> {
    return this.http
      .delete<AsyncData<T>>(mergeUrl(url), this.httpOptions)
      .pipe(catchError((err: HttpErrorResponse) => this.handleError(err)));
  }
  private handleError(error: HttpErrorResponse) {
    this.router.navigate(['/error']);
    console.log(error);
    if (error.error instanceof ErrorEvent) {
      console.error('An error occurred:', error.error.message);
    } else {
      console.error(
        `Backend returned code ${error.status}, ` + `body was: ${error.error}`
      );
    }
    return throwError('Something bad happened; please try again later.');
  }
}
